package com.frank.wechat.handler;

import com.frank.common.utils.StringUtil;
import com.frank.wechat.redis.RedisUtil;
import com.frank.wechat.utils.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/21
 * @description
 */

@Slf4j
@Component
public class ReceiveTextMessageHandler implements WeChatMessageHandler {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WeChatMessageTypeEnum getMessageType() {
        return WeChatMessageTypeEnum.TEXT;
    }

    @Override
    public String handle(Map<String, String> messageBody) {
        log.info("接收到文本消息：{}", messageBody);
        String toUser = messageBody.get("ToUserName");
        String fromUser = messageBody.get("FromUserName");
        String content = messageBody.get("Content");
        String replyContent = "感谢来信，我们会越来越好的哦！";
        if ("club login".equalsIgnoreCase(content)) {
            String captcha = StringUtil.generateCaptchaCode(8);
            String buildKey = redisUtil.buildKey("login", "captcha", String.valueOf(captcha));
            redisUtil.setNx(buildKey, toUser, 5L, TimeUnit.MINUTES);
            replyContent = "您的验证码是：" + captcha + " ，五分钟有效期";
        }

        return MessageUtil.assembleTextMessageContent(toUser, fromUser, replyContent);
    }

}
